import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'dart:io';
import 'package:craze/common/index.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:craze/stores/index.dart';
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.dart';
import 'dart:ui';

class UploadShareView extends StatefulWidget {
  const UploadShareView({super.key});

  @override
  State<UploadShareView> createState() => _UploadShareViewState();
}

class _UploadShareViewState extends State<UploadShareView> {
  final TextEditingController _descController = TextEditingController();
  List<AssetEntity> _selectedAssets = [];
  List<File> _selectedFiles = [];
  bool _isPublishing = false;
  final ShareStore _shareStore = GetIt.instance<ShareStore>();

  Future<void> _pickImages() async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: 3,
        selectedAssets: _selectedAssets,
        requestType: RequestType.image,
        themeColor: Colors.blue,
      ),
    );
    if (result != null) {
      final files = <File>[];
      for (final asset in result) {
        final file = await asset.file;
        if (file != null) files.add(file);
      }
      setState(() {
        _selectedAssets = result;
        _selectedFiles = files;
      });
    }
  }

  void _removeImage(int index) {
    setState(() {
      _selectedAssets.removeAt(index);
      _selectedFiles.removeAt(index);
    });
  }

  Future<void> _handlePublish() async {
    if (_selectedFiles.length != 3) {
      MyToast.showError(context, 'Please select exactly 3 images');
      return;
    }
    if (_descController.text.trim().isEmpty) {
      MyToast.showError(context, 'Please enter introduction');
      return;
    }
    setState(() => _isPublishing = true);
    final imagePaths = _selectedFiles.map((f) => f.path).toList();
    final share = await _shareStore.createShare(
      _descController.text.trim(),
      imagePaths,
    );
    setState(() => _isPublishing = false);
    if (share != null && mounted) {
      await _shareStore.loadShares();
      GoRouter.of(context).pop(true);
      MyToast.showSuccess(context, 'Share released successfully');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: 1.sw,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 16.h),
                // 顶部返回和标题
                Row(
                  children: [
                    GestureDetector(
                      onTap: () => Navigator.of(context).pop(),
                      child: Icon(
                        MyIcons.iconBack,
                        color: Colors.white,
                        size: 24.sp,
                      ),
                    ),
                    Expanded(
                      child: Center(
                        child: Text(
                          'Release',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 22.sp,
                            fontWeight: FontWeight.w400,
                            fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 24.h),
                // 介绍
                Text(
                  'Introduction',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(height: 13.h),
                Container(
                  height: 160.h,
                  alignment: Alignment.topLeft,
                  padding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 8.h,
                  ),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment(0.50, 0.00),
                      end: Alignment(0.50, 0.86),
                      colors: [
                        Color(0xFF0076FF).withAlpha(60),
                        Color(0xFF045EC6).withAlpha(60),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(10.r),
                    border: Border.all(color: MyColors.blue, width: 1.w),
                  ),
                  child: TextField(
                    controller: _descController,
                    maxLines: null,
                    minLines: 4,
                    style: TextStyle(color: Colors.white, fontSize: 16.sp),
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: 'Please enter introduction',
                      hintStyle: TextStyle(color: Colors.white.withAlpha(180)),
                    ),
                    textInputAction: TextInputAction.done,
                  ),
                ),
                SizedBox(height: 24.h),
                // 封面图片
                Text(
                  'Cover Image',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(height: 13.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children:
                      List.generate(3, (i) {
                        final boxSize =
                            (1.sw - 40.w - 24.w) / 3; // 40.w padding, 2*12.w 间距
                        if (i < _selectedFiles.length) {
                          return SizedBox(
                            width: boxSize,
                            height: boxSize,
                            child: Stack(
                              children: [
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(10.r),
                                  child: Image.file(
                                    _selectedFiles[i],
                                    width: boxSize,
                                    height: boxSize,
                                    fit: BoxFit.cover,
                                  ),
                                ),
                                Positioned(
                                  right: 0.w,
                                  bottom: 0.h,
                                  child: GestureDetector(
                                    onTap: () => _removeImage(i),
                                    child: Container(
                                      width: 36.w,
                                      height: 30.w,
                                      decoration: BoxDecoration(
                                        gradient: LinearGradient(
                                          begin: Alignment(0.50, 0.00),
                                          end: Alignment(0.50, 0.86),
                                          colors: [
                                            Color(0xFF0076FF).withAlpha(180),
                                            Color(0xFF045EC6).withAlpha(180),
                                          ],
                                        ),
                                        borderRadius: BorderRadius.only(
                                          topLeft: Radius.circular(10.r),
                                          bottomRight: Radius.circular(10.r),
                                        ),
                                      ),
                                      child: Icon(
                                        MyIcons.iconDelete,
                                        color: Colors.white,
                                        size: 28.sp,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          );
                        } else {
                          return GestureDetector(
                            onTap: _pickImages,
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(10.r),
                              child: BackdropFilter(
                                filter: ImageFilter.blur(
                                  sigmaX: 10,
                                  sigmaY: 10,
                                ),
                                child: Container(
                                  width: boxSize,
                                  height: boxSize,
                                  decoration: BoxDecoration(
                                    gradient: LinearGradient(
                                      begin: Alignment(0.50, 0.00),
                                      end: Alignment(0.50, 0.86),
                                      colors: [
                                        Color(0xFF0076FF).withAlpha(60),
                                        Color(0xFF045EC6).withAlpha(60),
                                      ],
                                    ),
                                    borderRadius: BorderRadius.circular(10.r),
                                    border: Border.all(
                                      color: MyColors.blue,
                                      width: 1.w,
                                    ),
                                  ),
                                  child: Center(
                                    child: Icon(
                                      MyIcons.iconAdd,
                                      color: Colors.white,
                                      size: 28.sp,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          );
                        }
                      }).asMap().entries.map((e) {
                        // 添加间距
                        final idx = e.key;
                        final widget = e.value;
                        if (idx == 2) return widget;
                        return Padding(
                          padding: EdgeInsets.only(right: 12.w),
                          child: widget,
                        );
                      }).toList(),
                ),
                const Spacer(),
                // 发布按钮
                GestureDetector(
                  onTap: _handlePublish,
                  child: Container(
                    height: 52.h,
                    width: double.infinity,
                    decoration: ShapeDecoration(
                      gradient: LinearGradient(
                        begin: Alignment(0.50, 0.00),
                        end: Alignment(0.50, 0.86),
                        colors: [Color(0xFF0076FF), Color(0xFF045EC6)],
                      ),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30.r),
                      ),
                    ),
                    child: Center(
                      child:
                          _isPublishing
                              ? SizedBox(
                                width: 24.w,
                                height: 24.w,
                                child: CircularProgressIndicator(
                                  color: Colors.white,
                                  strokeWidth: 2,
                                ),
                              )
                              : Text(
                                'Release',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18.sp,
                                  fontFamily:
                                      GoogleFonts.mochiyPopOne().fontFamily,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                    ),
                  ),
                ),
                SizedBox(height: 64.h),
                // Eula
                GestureDetector(
                  onTap: () {
                    WangYe.openUrl(
                      'https://www.freeprivacypolicy.com/live/d6a9a407-9d63-42af-9bc0-471389957c78',
                    );
                  },
                  child: Align(
                    alignment: Alignment.center,
                    child: Text(
                      'EULA',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.sp,
                        fontFamily: GoogleFonts.inter().fontFamily,
                        fontWeight: FontWeight.w400,
                        decoration: TextDecoration.underline,
                      ),
                    ),
                  ),
                ),
                SizedBox(height: 26.h),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
